package com.chatplus.application.common.crypto;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import org.apache.commons.lang3.StringUtils;

import java.io.InputStream;

public class RequestMessageDecryptorRSAImpl implements RequestMessageDecryptor {

    static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(RequestMessageDecryptorRSAImpl.class);

    private final RSA rsa;

    public RequestMessageDecryptorRSAImpl(String privateKeyStr, String publicKeyStr) {
        this.rsa = new RSA(privateKeyStr, publicKeyStr);
    }

    @Override
    public byte[] decrypt(byte[] bytes) {
        return rsa.decrypt(bytes, KeyType.PrivateKey);
    }

    @Override
    public byte[] decrypt(InputStream data) {
        return rsa.decrypt(data, KeyType.PrivateKey);
    }

    @Override
    public String decrypt(String data) {
        if (StringUtils.isBlank(data)) {
            return data;
        }
        if (!Base64.isBase64(data) && !HexUtil.isHexNumber(data)) {
            LOGGER.message("非Base64、Hex编码密文，直接返回原始数据").context("data", data).warn();
            return data;
        }
        try {
            return rsa.decryptStr(data, KeyType.PrivateKey);
        } catch (Exception e) {
            LOGGER.message("RSA解密失败，直接返回原始数据").context("data", data).error();
            return data;
        }
    }
}
